//
//  MyBankCardViewController.m
//  PPDL
//
//  Created by 王洋 on 2019/7/24.
//  Copyright © 2019 王洋. All rights reserved.
//

#import "BankCardCell.h"
#import "BankCardModel.h"

#import "MyBankCardViewController.h"
#import "AddBankCardViewController.h"

@interface MyBankCardViewController () <UITableViewDelegate, UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UITableView *tableview;

@property (nonatomic, strong) NSMutableArray <BankCardModel *> *cardArray;

@end

@implementation MyBankCardViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initView];

}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self request_BankCardList];
}

- (void)request_BankCardList {
    
    NSDictionary *dic = @{}.mutableCopy;
    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,TT_MEMBER_BANKCARD_LIST];
    
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        
        if ([data isKindOfClass:[NSDictionary class]]) {
            
            NSString * code = [data valueForKey:@"code"];
            if ([code isEqualToString:@"200"]) {

                NSArray *resultArray = [data valueForKey:@"data"];
                
                if (resultArray.count == 0) {
                    [[TTNoResultManager shareManager] showNoResultWithStateInView:self.tableview errorCode:kTTViewStateNoData btnTitle:@"刷新试试" didPressButton:^{
                        [self request_BankCardList];
                    }];
                }
                
                if (resultArray.count > 0) {
                    [[TTNoResultManager shareManager] hideNoResultWithView:self.tableview];
                }
                
                if ([resultArray isKindOfClass:[NSArray class]]) {
                    
                    [self.cardArray removeAllObjects];
                    for (int i = 0; i<resultArray.count; i++) {
                        
                        NSDictionary *cardDic = resultArray[i];
                        BankCardModel *model = [BankCardModel new];
                        model.bankName = [cardDic valueForKey:@"bankName"];
                        model.cardTypeName = [cardDic valueForKey:@"cardTypeName"];
                        model.bankCardID = [cardDic valueForKey:@"bankNumber"];
                        model.ID = [cardDic valueForKey:@"id"];
//                        model.isDefault = YES;
                        model.userName = [cardDic valueForKey:@"name"];
                        model.userPhoneNum = [cardDic valueForKey:@"phone"];

                        [self.cardArray addObject:model];
                    }

                    [[TTNoResultManager shareManager] hideNoResultWithView:self.tableview];
                } else {
                    
                    [[TTNoResultManager shareManager] showNoResultWithStateInView:self.tableview errorCode:kTTViewStateNoData btnTitle:@"" didPressButton:^{
                        [self request_BankCardList];
                        
                    }];
                }
                
            } else {
                
                [SVProgressHUD showErrorWithStatus:[data valueForKey:@"msg"]];
                [SVProgressHUD dismissWithDelay:1];
            }
        } else {
            
        }
        
        [self.tableview reloadData];

        [[TTNoResultManager shareManager] hideNoResultWithView:self.view];
        
    } FailedBlock:^(NSError * _Nonnull error) {
        
        WEAKSELF
        [[TTNoResultManager shareManager] showNoResultWithStateInView:self.view errorCode:error.code btnTitle:@"重新加载" didPressButton:^{
            [weakSelf request_BankCardList];
        }];
    }];
}

- (void)request_deleteBankCardWithID:(NSString *)ID {
    
    NSDictionary *dic = @{}.mutableCopy;
    [dic setValue:ID forKey:@"id"];
    [dic setValue:@"1" forKey:@"isDel"];
    
    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,TT_MEMBER_BANKCARD_UPDATE];
    
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        
        if ([data isKindOfClass:[NSDictionary class]]) {
            
            [self alert:[data valueForKey:@"msg"]];

        } else {
            
        }
        
    } FailedBlock:^(NSError * _Nonnull error) {
        
    }];
    
}


- (void)initView {
    self.title = @"我的银行卡";
    
    self.tableview.delegate = self;
    self.tableview.dataSource = self;
    self.tableview.separatorStyle = UITableViewCellSeparatorStyleNone;

    [self.tableview registerNib:[UINib nibWithNibName:@"BankCardCell" bundle:nil] forCellReuseIdentifier:@"BankCardCellID"];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    BankCardCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BankCardCellID" forIndexPath:indexPath];
    cell.selectionStyle =UITableViewCellSelectionStyleNone;
    
    [cell fillCellWithModel:self.cardArray[indexPath.row]];

    cell.refreshItemModel = ^(BankCardModel * _Nonnull model) {
        
    };
    
    return cell;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.cardArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 90;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (self.changeBankCard) {
        self.changeBankCard(self.cardArray[indexPath.row]);
        [self.navigationController popViewControllerAnimated:YES];
    }
}

#pragma mark 左滑删除
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    return YES;
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewCellEditingStyleDelete;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        
    }
}

- (NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {
    WEAKSELF
    UITableViewRowAction *deleteRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:@"删除" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {

        [weakSelf alert:@"是否删除当前银行卡" leftTitle:@"取消" Action:^(UIAlertAction * _Nonnull action) {
            
        } rightTitle:@"确定" Action:^(UIAlertAction * _Nonnull action) {
            
            [self request_deleteBankCardWithID:self.cardArray[indexPath.row].ID];
            
            [weakSelf.cardArray removeObjectAtIndex:indexPath.row];
            [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
            
            [tableView reloadData];
            
            if (self.cardArray.count == 0) {
                
                [[TTNoResultManager shareManager] showNoResultWithStateInView:self.tableview errorCode:kTTViewStateNoData btnTitle:@"刷新试试" didPressButton:^{
                    [self request_BankCardList];
                }];
            }
            

        }];
    }];
    deleteRowAction.backgroundColor = PP_Default_Color_Red_FF3737;
    
    UITableViewRowAction *editRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:@"编辑" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        
        AddBankCardViewController *VC =  [AddBankCardViewController new];
        VC.vcTitle = @"修改银行卡";
        VC.type = EditBankCardType_Update;

        if (weakSelf.cardArray.count > indexPath.row) {
            VC.defaultModel = weakSelf.cardArray[indexPath.row];
        }
        [weakSelf.navigationController pushViewController:VC animated:YES];
    }];
    editRowAction.backgroundColor = PP_Default_Color_Orange_E8AC44;
    
    return @[deleteRowAction,editRowAction];
}

- (IBAction)addBankCard:(id)sender {
    
    AddBankCardViewController *VC =  [AddBankCardViewController new];
    VC.type = EditBankCardType_Add;
    VC.vcTitle = @"添加银行卡";
    [self.navigationController pushViewController:VC animated:YES];
}

- (NSMutableArray<BankCardModel *> *)cardArray {
    
    if (!_cardArray) {
        _cardArray = [[NSMutableArray alloc] init];
    }
    return _cardArray;
}

@end
